package com.atguigu.gmall.activity.controller;


import com.atguigu.gmall.activity.service.SeckillService;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.order.OrderInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/api/seckill")
@RestController
public class SeckillController {

    @Autowired
    SeckillService seckillService;


    /**
     * 返回当天参与秒杀的所有商品
     * 给redis中缓存一份
     *
     * @return
     */
    @GetMapping("/current/goods")
    public List<SeckillGoods> getCurrentSeckillGoods(){
        //查询redis
        //List<SeckillGoods> list = seckillService.getCurrentSeckillGoods();
        //从本地缓存中拿
        List<SeckillGoods> list = seckillService.getCurrentSeckillGoodsFromCache();
        if (CollectionUtils.isEmpty(list)){
            //主动补偿逻辑
            list = seckillService.getCurrentSeckillGoods();
        }
        return list;
    }

    @GetMapping("/goods/{skuId}")
    public SeckillGoods getSeckillGoodsDetail(@PathVariable("skuId") Long skuId){
/*        //拿到所有需要秒杀的商品
        List<SeckillGoods> seckillGoods = seckillService.getCurrentSeckillGoods();
        //找到当前商品并返回信息，秒杀商品很多，快速拿到秒杀商品
        SeckillGoods goods = seckillGoods.stream().filter((good) -> {
            return good.getSkuId().equals(skuId);
        }).findFirst().get();*/

        SeckillGoods goods = seckillService.getSeckillGoodsById(skuId);

        return goods;
    }

    @GetMapping("/auth/user/seckillorder")
    public OrderInfo getUserSeckillOrderInfo(HttpServletRequest request) throws JsonProcessingException {
        String userId = AuthContextHolder.getUserId(request);
        OrderInfo orderInfo = seckillService.getUserSeckillOrderInfo(userId);
        return orderInfo;
    }

}
